import { createApp } from "vue";
import { createPinia } from "pinia";
import * as ElementPlusIconsVue from "@element-plus/icons-vue";
import {
  renderWithQiankun,
  qiankunWindow,
  QiankunProps,
} from "vite-plugin-qiankun/dist/helper";
import { useMainAppStores } from "./stores/mainApp";
import App from "./App.vue";
import router from "@/router/router";
import SvgIcon from "@/components/common/svgIcon.vue";
import ContextMenu from "@/directives/customRightMenu/index";
import "@/assets/iconfont/iconfont.js";

import "./style.less";
import "./theme.less";
import "element-plus/dist/index.css";

let instance: any = null;

const render = (props: QiankunProps = {}) => {
  const { container } = props;
  const myApp: string | Element =
    container?.querySelector("#neteaseMusic") || "#neteaseMusic"; // 避免 id 重复导致微应用挂载失败

  const app = createApp(App);

  for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component);
  }
  const Pinia = createPinia();
  app.use(Pinia);
  app.use(router);
  app.use(ContextMenu);
  app.component("SvgIcon", SvgIcon);
  app.mount(myApp);

  const mainApp = useMainAppStores();
  mainApp.setMainAppStore(props.getGlobalState);
  instance = app;
};

const initQianKun = () => {
  renderWithQiankun({
    bootstrap() {
      console.log("微应用：bootstrap");
    },
    mount(props) {
      // 获取主应用传入数据
      console.log("微应用：mount", props);

      render(props);
    },
    unmount(props) {
      console.log("微应用：unmount", props);
      if (instance !== null) {
        instance.unmount();
      }
    },
    update(props) {
      console.log("微应用：update", props);
    },
  });
};

qiankunWindow.__POWERED_BY_QIANKUN__ ? initQianKun() : render();
